#include "TTASK.h"
#include "FreeRTOS.h"
#include "timers.h"
#include "log.h"
extern LOG *log_1;

TTASK::TTASK() : timerHandle(nullptr) {}

TTASK::~TTASK() {
    if (timerHandle != nullptr) {
        xTimerDelete(timerHandle, portMAX_DELAY);
    }
}

void TTASK::start(uint32_t intervalMs, std::function<void()> callback, TimerType type) {
    stop(); // 停止现有定时器

    userCallback = callback;
    TickType_t ticks = pdMS_TO_TICKS(intervalMs);
    UBaseType_t autoReload = (type == TimerType::PERIODIC) ? pdTRUE : pdFALSE;

    timerHandle = xTimerCreate(
        "TTASK Timer",
        ticks,
        autoReload,
        this, // 传递this指针作为ID
        [](TimerHandle_t xTimer) {
            TTASK* instance = static_cast<TTASK*>(pvTimerGetTimerID(xTimer));
            if (instance && instance->userCallback) {
                instance->userCallback();
            }
        }
    );

    if (timerHandle) {
        xTimerStart(timerHandle, 0);
        // 立即执行周期性任务（可选）
        if (type == TimerType::PERIODIC && callback) {
            callback();
        }
    }
}

void TTASK::stop() {
    if (timerHandle) {
        xTimerStop(timerHandle, 0);
        xTimerDelete(timerHandle, portMAX_DELAY);
        timerHandle = nullptr;
    }
}